package cn.tiansu.eway.kylinengine.service;

import java.net.URLDecoder;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import cn.tiansu.eway.kylinengine.utils.Base64;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/**
 * http的请求客户端，json格式
 * 
 * @Title: HttpClientMethod.java
 * @Description: TODO
 * @author: 吴鹏
 * @date: 2015年8月31日
 * 
 *
 */
public class HttpClientMethod
{
	private final static Logger log = Logger.getLogger(HttpClientMethod.class);

	private static Header header = new BasicHeader("Authorization", "Basic "
			+ Base64.encode("ADMIN:KYLIN".getBytes()));

	/**
	 * put请求
	 * 
	 * @param url
	 *            请求url
	 * @param jsonParam
	 *            入参
	 * @param noNeedResponse
	 *            是否需要response
	 * @return
	 */
	public static JSONObject httpPut(String url, JSONObject jsonParam,
			boolean noNeedResponse)
	{
		// post请求返回结果
		HttpClient httpClient = new DefaultHttpClient();
		JSONObject jsonResult = null;
		
		log.info("httpPut url is "+url+",jsonParam is "+jsonParam);
		try
		{
			HttpPut method = new HttpPut(url);
			if (null != jsonParam)
			{
				// 解决中文乱码问题
				StringEntity entity = new StringEntity(jsonParam.toString(),
						"utf-8");
				entity.setContentEncoding("UTF-8");
				entity.setContentType("application/json");
				method.setEntity(entity);
			}

			method.setHeader(header);

			HttpResponse result = httpClient.execute(method);
			url = URLDecoder.decode(url, "UTF-8");
			log.debug("method : " + method);

			int code = result.getStatusLine().getStatusCode();
			log.debug("code=" + code);
			/** 请求发送成功，并得到响应 **/
			if (code == 200)
			{
				String str = "";
				try
				{
					/** 读取服务器返回过来的json字符串数据 **/
					str = EntityUtils.toString(result.getEntity());
					if (noNeedResponse)
					{
						return null;
					}
					/** 把json字符串转换成json对象 **/
					jsonResult = JSONObject.parseObject(str);

					log.debug(jsonResult);
				} catch (Exception e)
				{
					log.error("post请求提交失败:" + url, e);
				}
			}
		} catch (Exception e)
		{
			log.error("post请求提交失败:" + url, e);
		}
		return jsonResult;
	}

	/**
	 * post请求
	 * 
	 * @param url
	 *            url地址
	 * @param jsonParam
	 *            参数
	 * @param noNeedResponse
	 *            不需要返回结果
	 * @return
	 */
	public static JSONObject httpPost(String url, JSONObject jsonParam,
			boolean noNeedResponse)
	{
		// post请求返回结果
		HttpClient httpClient = new DefaultHttpClient();
		JSONObject jsonResult = null;
		log.debug("httpPost url is "+url+",jsonParam is "+jsonParam);
		try
		{
			HttpPost method = new HttpPost(url);
			if (null != jsonParam)
			{
				// 解决中文乱码问题
				StringEntity entity = new StringEntity(jsonParam.toString(),
						"utf-8");
				entity.setContentEncoding("UTF-8");
				entity.setContentType("application/json");
				method.setEntity(entity);
			}

			method.setHeader(header);

			HttpResponse result = httpClient.execute(method);
			url = URLDecoder.decode(url, "UTF-8");
			log.debug("method : " + method);

			int code = result.getStatusLine().getStatusCode();
			log.info("code=" + code);
			/** 请求发送成功，并得到响应 **/
			if (code == 200)
			{
				String str = "";
				try
				{
					/** 读取服务器返回过来的json字符串数据 **/
					str = EntityUtils.toString(result.getEntity());
					if (noNeedResponse)
					{
						return null;
					}
					/** 把json字符串转换成json对象 **/
					jsonResult = JSONObject.parseObject(str);

					log.debug(jsonResult);
				} catch (Exception e)
				{
					log.error("post请求提交失败:" + url, e);
				}
			}
		} catch (Exception e)
		{
			log.error("post请求提交失败:" + url, e);
		}
		return jsonResult;
	}

	/**
	 * 发送get请求
	 * 
	 * @param url
	 *            路径
	 * @return
	 */
	public static JSONObject httpGet(String url)
	{
		// get请求返回结果
		JSONArray arr = null;
		
		log.info("httpGet url is "+url);
		try
		{
			DefaultHttpClient client = new DefaultHttpClient();
			// 发送get请求
			HttpGet request = new HttpGet(url);

			request.setHeader(header);
			HttpResponse response = client.execute(request);

			/** 请求发送成功，并得到响应 **/
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
			{
				/** 读取服务器返回过来的json字符串数据 **/
				String strResult = EntityUtils.toString(response.getEntity());

				/** 把json字符串转换成json对象 **/
				arr = JSONObject.parseArray(strResult);
				log.debug("JSONArray=" + arr);
			} else
			{
				log.debug("get请求提交失败:" + url);
				log.debug("response.getStatusLine().getStatusCode():"
						+ response.getStatusLine().getStatusCode());
			}
		} catch (Exception e)
		{
			log.error("get请求提交失败:" + url, e);
		}
		return arr.getJSONObject(0);
	}
}
